import pageConfig from "@/config";
import { getToken, removeToken } from "@/utils/auth";
// import errorCode from "@/utils/errorCode";
import { toast, tansParams } from "@/utils/common";

let timeout = 10000;
const baseUrl = pageConfig.baseUrl;

/*
  接口处理函数
*/
function apiAxios(method, url, params, requestConfig) {
  const config = { method, url, params, ...requestConfig };
  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false;
  config.header = config.header || {};
  if (getToken() && !isToken) {
    config.header["Authorization"] = "Bearer " + getToken();
  }
  // get请求映射params参数
  if (method === "get" || (method === "put" && requestConfig.lickGet)) {
    let requestUrl = url + "?" + tansParams(params);
    config.url = requestUrl;
  }
  let requestParams = {};
  for (let key in config.params) {
    if (config.params[key] !== null) {
      requestParams[key] = config.params[key];
    }
  }
  return new Promise((resolve, reject) => {
    uni
      .request({
        method: method || "get",
        timeout: config.timeout || timeout,
        url: config.baseUrl || baseUrl + config.url,
        params: requestParams,
        data: requestParams,
        header: config.header,
        dataType: "json",
      })
      .then((response) => {
        let [error, res] = response;
        if (error) {
          toast("后端接口连接异常");
          reject("后端接口连接异常");
          return;
        }
        const code = res.data.code || 200;
        // const msg = errorCode[code] || res.data.msg || errorCode["default"];
        if (code === 200) {
          resolve(res.data);
        } else if (code === 401) {
          removeToken();
          uni.removeStorageSync("sessionKey");
          uni.removeStorageSync("userInfo");
          uni.removeStorageSync("cartProduct");
          uni.removeStorageSync("selectedAddress");
          uni.showToast({
            title: "登录失效，请重新登录",
            icon: "none",
          });
          setTimeout(() => {
            uni.navigateTo({
              url: "/pages/login",
            });
          }, 1500);
        } else {
          uni.showToast({
            title: res.data.msg,
            icon: "none",
          });
        }
      })
      .catch((error) => {
        let { message } = error;
        if (message === "Network Error") {
          message = "后端接口连接异常";
        } else if (message.includes("timeout")) {
          message = "系统接口请求超时";
        } else if (message.includes("Request failed with status code")) {
          message = "系统接口" + message.substr(message.length - 3) + "异常";
        }
        toast(message);
        reject(error);
      });
  });
}

// 返回在vue模板中的调用接口
export default {
  get: function (url, params = {}, requestConfig = {}) {
    return apiAxios("get", url, params, requestConfig);
  },
  post: function (url, params = {}, requestConfig = {}) {
    return apiAxios("post", url, params, requestConfig);
  },
  put: function (url, params = {}, requestConfig = {}) {
    return apiAxios("put", url, params, requestConfig);
  },
  delete: function (url, params = {}, requestConfig = {}) {
    return apiAxios("delete", url, params, requestConfig);
  },
  file: function (url, params = {}, requestConfig = {}) {
    return apiAxios("file", url, params, requestConfig);
  },
};
